<template>

  <!-- 表格模块-->
  <div class="tableRow">

    <el-row class="select-list" v-permission="'bus:structure:query'">
      <el-form :inline="true" ref="selectForm" label-position="right" label-width="80px" :model="selectFormModel"
        size="mini">
        <el-form-item label="标题" prop="title">
          <el-input v-model="selectFormModel.title" placeholder="标题" style="width: 200px" clearable
            @keyup.enter.native="onSearch" />
        </el-form-item>
        <el-form-item label="年月" prop="monthId">
          <el-date-picker v-model="selectFormModel.monthId" type="month" placeholder="选择年月" style="width: 200px"
            clearable @keyup.enter.native="onSearch" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select value="" v-model="selectFormModel.status" placeholder="用户状态" style="width: 200px">
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" plain round @click="onSearch">搜索
          </el-button>
          <el-button type="warning" icon="el-icon-refresh" size="mini" plain round @click="onRefreshSelectForm()">重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 表格操作按钮 增删改查-->
    <el-row class="toolbar">
      <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd"
        v-permission="'bus:structure:add'">
        新增
      </el-button>
      <el-button type="info" icon="el-icon-edit" :disabled="dialog.isBatchEditDisabled" size="mini" plain
        @click="handleEdit" v-permission="'bus:structure:edit'"> 编辑
      </el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="dialog.isBatchRemoveDisabled" size="mini" plain
        @click="handleBatchDelete" v-permission="'bus:structure:remove'"> 删除
      </el-button>
    </el-row>

    <!-- 表格模块 -->
    <data-table ref="dataTable" :api="getStructureList" :options="options" :columns="columns" :operates="operates"
      :query="selectFormModel" @handle-selection-change="handleSelectionChange" />

    <el-dialog :title="dialog.title" :visible.sync="dialog.dialogImportVisible" :modal-append-to-body="false"
      :destroy-on-close="false" custom-class="body-wrapper" @close="closeUploadDialog" width="500px">

      <el-upload drag ref="upload" :action="importRecord" :show-file-list="true" :auto-upload="false" :headers="headers"
        :data="{ id: this.dialog.rowId, force: this.dialog.dialogImportForce + '' }" accept=".xls,.xlsx"
        :on-success="uploadSuccess" :on-exceed="handleExceed" :on-error="uploadError" :limit="1">
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

        <div class="el-upload__tip" slot="tip">
          <el-alert title="只能上传xls/xlsx文件" type="warning" show-icon>
          </el-alert>
        </div>
      </el-upload>
      <div>
        <span style="color: #E6A23C;">后台校验？点击这里&nbsp;</span><el-switch v-model="dialog.dialogImportForce"
          active-color="#13ce66" inactive-color="#ff4949" active-value="1" inactive-value="0"></el-switch>
        <span style="color: #E6A23C;">&nbsp;强制提交</span>
      </div>

      <div slot="footer" class="dialog-footer">

        <el-button @click="dialog.dialogImportVisible = false" size="medium">取 消</el-button>
        <el-button type="primary" @click="submitUpload" size="medium">确 定</el-button>
      </div>
    </el-dialog>
    <div>
      <el-dialog :title="dialog.title" :visible.sync="dialog.dialogExportVisible" :modal-append-to-body="false"
        :destroy-on-close="true" custom-class="body-wrapper" @close="closeDownloadDialog" width="500px">
        <div>dssss</div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialog.dialogExportVisible = false" size="medium">取 消</el-button>
          <el-button type="primary" @click="submitDownData" size="medium">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<!-- 脚本模块  -->
<script lang="ts">
import { Component, Ref, Vue } from 'vue-property-decorator';
import DataTable from '@/components/DataTable/DataTable.vue';

import {
  addStructure,
  checkStructureNameUnique,
  getStructureList,
  removeStructure,
  updateStructure,
  downloadStructureData
} from '@/api/investStructure';
import store from '@/store';
import { validateForm } from '@/utils';

@Component({ components: { DataTable } })
export default class Area extends Vue {
  data: Array<any> = [];
  @Ref('structureForm') private structureForm: any;
  @Ref('treeSelect') private treeSelect: any;
  @Ref('selectForm') private selectForm: any;
  @Ref('dataTable') private dataTable: any;
  @Ref('upload') private upload: any;
  private getStructureList: any = getStructureList;

  columns: any = [
    {
      label: 'ID',
      prop: 'id',
      width: 150,
      hide: true
    },
    {
      label: '标题',
      prop: 'title',

      render: function (createElement, row) {

        let elements: any = [];
        if (row && row.row && row.row.title) {

          const el = createElement("h4", {
            domProps: { innerHTML: row.row.title },
            style: {
              color: '#606266',
            },
          });
          elements.push(el);
        }
        if (row && row.row && row.row.subTitle) {
          const el = createElement("h3", {
            domProps: { innerHTML: row.row.subTitle },
            style: {
              color: '#303133',
            },
          });
          elements.push(el);
        }
        return createElement("div", { class: "box" }, elements)
      }
    },
    {
      label: '年月',
      prop: 'monthId',
      formatter: function (row: any, col: any) {
        if (row && row.monthId) {
          return row.monthId.toString().substring(0, 4) + '年' + row.monthId.toString().substring(5) + '月';
        }
        return '';
      }
    },
    {
      label: '状态', prop: 'status', sortable: 'custom', render: function (createElement, row) {
        if (row && row.row && row.row.status === '0') {
          return createElement('el-tag', {
            attrs: {
              type: 'success'
            }
          }, ['正常']
          );
        } else if (row && row.row && row.row.status === '1') {
          return createElement('el-tag', {
            attrs: {
              type: 'warning'
            }
          }, ['停用']
          );
        } else {
          return createElement('el-tag', {
            attrs: {
              type: 'danger'
            }
          }, ['未知']
          );
        }
      }
    },
    { label: '创建时间', prop: 'createTime', sortable: 'custom', width: 160, showOverflowTooltip: true }
  ];

  get importRecord() {
    return process.env.VUE_APP_BASE_API + '/bus/structure/importRecord';
  }

  operates: any = {
    width: 250,
    fixed: 'right',
    list: [
      {
        label: '',
        type: 'warning',
        icon: 'el-icon-edit',
        plain: true,
        disabled: () => {
          return false;
        },
        permission: 'bus:category:edit',
        method: (index, row) => {
          this.handleEdit(index, row);
        }
      },
      {
        label: '',
        type: 'danger',
        icon: 'el-icon-delete',
        plain: true,
        disabled: () => {
          return false;
        },
        permission: 'bus:category:remove',
        method: (index, row) => {
          this.handleDelete(index, row);
        }
      },
      {
        label: '',
        type: 'danger',
        icon: 'el-icon-upload',
        plain: true,
        disabled: () => {
          return false;
        },
        permission: 'bus:data:upload',
        method: (index, row) => {
          this.handleUpload(index, row);
        }
      },
      {
        label: '',
        type: 'danger',
        icon: 'el-icon-download',
        plain: true,
        disabled: () => {
          return false;
        },
        permission: 'bus:data:download',
        method: (index, row) => {
          this.handleDownload(index, row);
          this.downloadFormModel.structureId = row.id;
        }
      }
    ]
  };

  headers: any = {
    'Authorization': 'Bearer ' + store.getters.token
  };

  structureModel: any = {
    categoryId: 0,
    title: '',
    subTitle: '',
    monthId: 1,
    status: '0'
  };

  options: any = {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    multipleSelect: true, // 是否支持列表项选中功能
  };

  selectFormModel: any = {
    title: '',
    monthId: '',
    categoryId: '',
    status: '0'
  };

  downloadFormModel: any = {
    structureId: '',
  }

  structureFormRules: any = {
    categoryId: [
      { validator: this.validateParentNotSelf, trigger: 'change' },
    ],
    title: [
      { required: true, message: '标题不能为空', trigger: ['blur', 'change'] },
      { validator: this.validatNameUnique, trigger: 'blur' },
    ],
    subTitle: [
      { required: true, message: '副标题不能为空', trigger: ['blur'] }
    ]
  };
  dialog: any = {
    dialogFormVisible: false,
    title: '对话框',
    isEdit: false,
    rowId: '',
    dialogImportVisible: false,
    dialogExportVisible:false,
    dialogImportForce: "0",
    isBatchEditDisabled: true,
    isBatchRemoveDisabled: true,
    formData: [],
    selectParams: {
      clearable: true,
      placeholder: '请选择类别'
    },
    treeParams: {
      clickParent: true,
      filterable: true,
      accordion: true,
      data: [],
      props: {
        children: 'children',
        label: 'label',
        disabled: 'disabled',
        value: 'id'
      }
    }
  };

  /*验证区域名称是否唯一*/
  validatNameUnique(rule: any, value: any, callback: any) {
    checkStructureNameUnique({
      name: value,
      id: this.structureModel.id,
      parentId: this.structureModel.parentId
    }).then((res: any) => {
      if (res.data && res.data === '0') {
        callback();
      } else {
        callback(new Error('类别已经存在'));
      }
    }).catch((err: any) => {
      console.error(err);
      callback(new Error('类别已经存在'));
    })
  }

  /*上级类别不能是自己本身*/
  validateParentNotSelf(rule: any, value: any, callback: any) {
    if (value === this.structureModel.id) {
      callback(new Error('上级类别不能是自己本身'));
    } else {
      callback();
    }
  }

  closeUploadDialog() {
    this.dialog.dialogImportVisible = false;

    this.$nextTick(() => {
      this.upload.clearFiles();
    });
  }
  closeDownloadDialog() {
    this.dialog.dialogExportVisible = false;
  }

  /*新增*/
  handleAdd() {
    this.$router.push('/bus/structureAdd');
  }

  /*编辑*/
  handleEdit(index: number, row: any) {
    const id = (row && row.id) ? row.id : 0;
    if (id) {
      this.$router.push({ path: '/bus/structureAdd', query: { id: id } });
    }
  }

  handleDownload(index: number, row: any) {
    const id = (row && row.id) ? row.id : 0;
    this.dialog.rowId = id;
    this.dialog.title = '数据导出';
    this.dialog.dialogFormVisible = false;
    this.dialog.dialogImportVisible = false;
    this.dialog.dialogExportVisible = true;
    this.downloadFormModel.structureId = id;
  }

  handleUpload(index: number, row: any) {
    const id = (row && row.id) ? row.id : 0;
    this.dialog.rowId = id;
    this.dialog.title = '数据导入';
    this.dialog.dialogFormVisible = false;
    this.dialog.dialogImportVisible = true;
    this.dialog.dialogExportVisible = false;

  }



  /*批量删除*/
  handleBatchDelete() {
    //删除
    this.$confirm('确定要删除选定结构吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const ids: Array<any> = [];
      this.dialog.formData.forEach((item, index) => {
        ids[index] = item.id;
      });
      return removeStructure({ 'ids': ids });
    }).then((response: any) => {
      this.dataTable.refresh();
      this.$message.success(response.msg);
    }).catch((e) => {
      console.error(e);
    });
  }

  /*删除*/
  handleDelete(index: number, row: any) {
    this.$confirm('确定要删除该结构吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      return removeStructure({ 'ids': [row.id] });
    }).then((response: any) => {
      this.dataTable.refresh();
      this.$message.success(response.msg);
    }).catch((e) => {
      console.error(e);
    });
  }

  submitDownData(): void {
    downloadStructureData(this.downloadFormModel).then(res => {
      if (res && res.data) {
        (this as any).$download(res.data.fileName);
      }
    }).catch((e) => {
      console.error(e);
    });
  }

  submitForm(): void {
    this.structureForm.validate((valid: boolean) => {
      if (valid) {
        delete this.structureModel.children;
        if (this.dialog.isEdit) {
          //编辑
          updateStructure(this.structureModel).then((response: any) => {
            this.getData();
            this.reset();
            this.dialog.dialogFormVisible = false;
            this.$message.success(response.msg);
          }).catch((e) => {
            console.error(e);
            validateForm(e.data, this.structureForm, this.structureFormRules);
          });
        } else {
          //新增
          addStructure(this.structureModel).then((response: any) => {
            this.getData();
            this.reset();
            this.dialog.dialogFormVisible = false;
            this.$message.success(response.msg);
          }).catch((e) => {
            console.error(e);
            validateForm(e.data, this.structureForm, this.structureFormRules);
          });
        }
      }
    });
  }

  onSearch(): void {
    this.dataTable.refresh();
  }

  onRefreshSelectForm(): void {
    //恢复搜索默认信息
    this.selectForm.resetFields();
    this.onSearch();
  }

  /*选中事件*/
  handleSelectionChange(val): void {
    if (val) {
      this.dialog.isBatchRemoveDisabled = val.length <= 0;
      this.dialog.isBatchEditDisabled = val.length !== 1;
    }
    this.dialog.formData = val;
  }

  /*重置表单*/
  reset(): void {
    this.structureModel = {
      categoryId: 0,
      title: '',
      subTitle: 1,
      monthId: '',
      status: '0'
    };
    (this as any).resetForm('strucureForm');
  }

  /*关闭对话框*/
  closeDialog() {
    this.$nextTick(() => {
      this.reset();
    });
  }


  /*获取数据*/
  getData() {
    getStructureList().then(response => {
      this.data = response.data;
    }).catch((e) => {
      console.error(e);
    });
  }

  searchFun(value: any): void {
    this.treeSelect.filterFun(value);
  }

  handleExceed(files, fileList) {
    this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
  }

  /*上传*/
  submitUpload() {
    this.upload.submit();
  }

  /*上传成功*/
  uploadSuccess(res) {
    if (res.result) {//上传成功
      this.$message.success(`导入成功，${res.msg}`);
    } else {//上传失败
      this.$message.warning(`导入失败，${res.msg}`);
      this.upload.clearFiles();
    }
  }

  /*文件上传失败*/
  uploadError(res) {
    const result = JSON.parse(res.message);
    this.$message.error(`导入失败，${result.msg}`);
  }

  mounted() {
    this.getData();
  }


}
</script>

<style scoped lang="scss"></style>
